package web.server.io.handler.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.server.ioc.ApiStore;
import web.server.parameter.analysis.Request;

public class WebHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static final Logger log = LoggerFactory.getLogger(WebHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {

        String uri = fullHttpRequest.uri();
        HttpMethod method = fullHttpRequest.method();
        Request request = new Request(fullHttpRequest);
        String content = request.getContent();
        log.info(method  + " " + uri);
        log.info(content);
        Object[] objects = new Object[]{content};
        Object o = ApiStore.invokeApi(String.valueOf(method), uri, objects);
        assert o != null;
        log.info((String) o);
        ByteBuf byteBuf = Unpooled.copiedBuffer(o.toString().getBytes());
        FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);

        HttpHeaders headers = fullHttpResponse.headers();
        headers.add(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8");
        headers.set(HttpHeaderNames.CONTENT_LENGTH.toString(), byteBuf.readableBytes());

        ctx.writeAndFlush(fullHttpResponse);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
